<template>
  <div class="page-container">
    <!--工具栏-->
    <div class="toolbar" style="float:left;padding-top:10px;padding-left:15px;">
      <el-form :inline="true" :model="filters" :size="size">
        <el-form-item>
          <el-input v-model="filters.title" placeholder="标题"></el-input>
        </el-form-item>
        <el-form-item>
          <el-input v-model="filters.subtitle" placeholder="副标题"></el-input>
        </el-form-item>
        <el-form-item>
          <perm-button icon="fa fa-search" label="搜索" perms="info:article:list" type="primary" @click="findPage(null)"/>
        </el-form-item>
        <el-form-item>
          <perm-button icon="fa fa-plus" label="新增" perms="info:article:add" type="success" @click="handleAdd"/>
        </el-form-item>
      </el-form>
    </div>
    <div class="toolbar" style="float:right;padding-top:10px;padding-right:15px;">
      <el-form :inline="true" :size="size">
        <el-form-item>
          <el-button-group>
            <el-tooltip content="刷新" placement="top">
              <el-button icon="fa fa-refresh" @click="findPage(null)"></el-button>
            </el-tooltip>
            <el-tooltip content="列显示" placement="top">
              <el-button icon="fa fa-filter" @click="displayFilterColumnsDialog"></el-button>
            </el-tooltip>
            <el-tooltip content="导出" placement="top">
              <el-button icon="fa fa-file-excel-o"></el-button>
            </el-tooltip>
          </el-button-group>
        </el-form-item>
      </el-form>
      <!--表格显示列界面-->
      <table-column-filter-dialog ref="tableColumnFilterDialog" :columns="columns"
                                  @handleFilterColumns="handleFilterColumns">
      </table-column-filter-dialog>
    </div>
    <!--表格树内容栏-->
    <perm-table :page="page" :columns="columns" :selectionChange="selectionChange"
                :handleCurrentHandle="handleCurrentHandle" :loading="loading" size="mini"
                @findPage="findPage" @handleEdit="handleEdit" @handleDelete="handleDelete"
                permsEdit="info:article:update" permsDelete="info:article:delete">
    </perm-table>
    <!-- 新增修改界面 -->
    <el-dialog :title="!dataForm.articleId ? '新增文章' : '修改文章'" width="80%" :visible.sync="dialogVisible" :close-on-click-modal="false">
      <el-form :model="dataForm" :rules="dataRule" ref="dataForm" @keyup.enter.native="submitForm()"
               label-width="80px" :size="size" style="text-align:left;">
        <el-form-item label="标题" prop="title">
          <el-input v-model="dataForm.title" placeholder="文章标题"></el-input>
        </el-form-item>
        <el-row :gutter="20">
          <el-col :span="16">
            <el-form-item label="副标题" prop="subtitle">
              <el-input v-model="dataForm.subtitle" placeholder="文章副标题"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="分类名称" prop="categoryName">
            <popup-tree-input
              :data="popupTreeData" :props="popupTreeProps" :prop="dataForm.categoryName==null||dataForm.categoryName===''?'顶级分类':dataForm.categoryName"
              :nodeKey="''+dataForm.categoryId" :currentChangeHandle="handleTreeSelectChange">
            </popup-tree-input>
          </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="关键字" prop="keyword">
          <el-tag
            :key="tag"
            v-for="(tag, index) in dynamicTags"
            closable
            :type="randomType(index)"
            :disable-transitions="false"
            @close="handleClose(tag)">
            {{tag}}
          </el-tag>
          <el-input
            class="input-new-tag"
            v-if="inputVisible"
            v-model="inputValue"
            ref="saveTagInput"
            size="small"
            @keyup.enter.native="handleInputConfirm"
            @blur="handleInputConfirm"
          >
          </el-input>
          <el-button v-else class="button-new-tag" size="small" @click="showInput">+ 新增</el-button>
        </el-form-item>

        <el-form-item label="简介" prop="intro">
          <el-input type="textarea" v-model="dataForm.intro" placeholder="简介"></el-input>
        </el-form-item>
        <el-row :gutter="20">
          <el-col :span="6">
            <el-form-item label="作者" prop="author">
              <el-input v-model="dataForm.author" placeholder="作者"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="来源" prop="source">
              <el-input v-model="dataForm.source" placeholder="来源"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="来源链接" prop="url">
              <el-input v-model="dataForm.url" placeholder="来源链接"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="6">
            <el-form-item label="置顶" prop="ontop">
              <el-switch
                v-model="dataForm.ontop"
                active-color="#13ce66"
                inactive-color="#ff4949"
                active-value="已置顶"
                inactive-value="未置顶">
              </el-switch>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="推荐" prop="recommend">
              <el-switch
                v-model="dataForm.recommend"
                active-color="#13ce66"
                inactive-color="#ff4949"
                active-value="推荐"
                inactive-value="未推荐">
              </el-switch>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="发布" prop="pubstatus">
              <el-switch
                v-model="dataForm.pubstatus"
                active-color="#13ce66"
                inactive-color="#ff4949"
                active-value="已发布"
                inactive-value="未发布">
              </el-switch>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="排序编号" prop="orderNum">
              <el-input-number v-model="dataForm.orderNum" controls-position="right" :min="0" label="排序编号"></el-input-number>
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="内容" prop="content">
          <editor id="editor_id" :content="dataForm.content"
                  :resize-type="editorOption.resizeType"
                  :allow-preview-emoticons="editorOption.allowPreviewEmoticons"
                  :allow-image-remote="editorOption.allowImageRemote"
                  :allow-image-upload="editorOption.allowImageUpload"
                  :allow-file-manager="editorOption.allowFileManager"
                  :upload-json="editorOption.uploadJson"
                  :css-data="editorOption.cssData"
                  :width="editorOption.width"
                  :height="editorOption.height"
                  :items="editorOption.items"
                  :afterChange="editorOption.afterChange()"
                  pluginsPath="../../../../static/kindeditor/plugins/"
                  :loadStyleMode="false"
                  @on-content-change="onContentChange"></editor>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button :size="size"  @click="dialogVisible = false">取消</el-button>
        <el-button :size="size"  type="primary" :loading="editLoading" @click="submitForm()">确认</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import PopupTreeInput from '../../Component/PopupTreeInput/Index'
import PermButton from '../../Component/PermButton/Index'
import PermTable from '../../Component/PermTable/Index'
import TableColumnFilterDialog from '../../Component/TableColumnFilterDialog/Index'
import { baseUrl } from '../../../utils/global'

export default {
    name: 'Article',
    components: {
        PermTable,
        PermButton,
        PopupTreeInput,
        TableColumnFilterDialog
    },
    data: function() {
        return {
            size: 'small',
            loading: false,
            editLoading: false,
            filters: {
                title: '',
                subtitle: '',
                keyword: '',
                categoryId: '',
                intro: '',
                author: ''
            },
            filterColumns: [],
            columns: [],
            page: {},
            pageRequest: {
                current: 1,
                size: 10
            },
            dialogVisible: false,
            dataForm: {
                articleId: 0,
                title: '',
                categoryId: 0,
                categoryName: '',
                subtitle: '',
                keyword: '',
                intro: '',
                content: '',
                orderNum: 0,
                author: '',
                source: '',
                recommend: '未推荐',
                ontop: '未置顶',
                url: '',
                pubstatus: '未发布'
            },
            recommendList: ['未推荐', '推荐'],
            ontopList: ['未置顶', '已置顶'],
            pubstatusList: ['未发布', '已发布'],
            dataRule: {
                title: [{ required: true, message: '标题名称不能为空', trigger: 'blur' }],
                content: [{ required: true, message: '文章内容不能为空', trigger: 'blur' }],
                categoryName: [{ required: true, message: '文章分类不能为空', trigger: 'blur' }],
                author: [{ required: true, message: '作者不能为空', trigger: 'blur' }]
            },
            popupTreeData: [],
            popupTreeProps: {
                label: 'categoryName',
                children: 'children'
            },
            dynamicTags: [],
            inputVisible: false,
            inputValue: '',
            editorOption: {
                resizeType: 1,
                allowPreviewEmoticons: false,
                allowImageUpload: true,
                allowImageRemote: true,
                allowFileManager: true,
                uploadJson: baseUrl + '/common/kindeditor/image/upload',
                cssData: 'body, td {font:14px/1.5 "sans serif",tahoma,verdana,helvetica;}',
                width: '100%',
                height: '350',
                items: ['source', '|', 'undo', 'redo', '|', 'preview', 'print', 'template', 'code', 'cut', 'copy', 'paste',
                    'plainpaste', 'wordpaste', '|', 'justifyleft', 'justifycenter', 'justifyright',
                    'justifyfull', 'insertorderedlist', 'insertunorderedlist', 'indent', 'outdent', 'subscript',
                    'superscript', 'clearhtml', 'quickformat', 'selectall', '|', 'fullscreen',
                    'formatblock', 'fontname', 'fontsize', '|', 'forecolor', 'hilitecolor', 'bold',
                    'italic', 'underline', 'strikethrough', 'lineheight', 'removeformat', '|', 'image',
                    'table', 'hr', 'emoticons', 'baidumap', 'pagebreak', 'anchor', 'link', 'unlink'],
                afterChange: function() {
                }
            }
        }
    },
    methods: {
        handleClose(tag) {
            this.dynamicTags.splice(this.dynamicTags.indexOf(tag), 1)
            this.dataForm.keyword = this.dynamicTags.join(',')
        },
        randomType(index) {
            const types = ['', 'success', 'info', 'warning', 'danger']
            const i = index % types.length
            return types[i]
        },
        showInput() {
            this.inputVisible = true
            this.$nextTick(_ => {
                this.$refs.saveTagInput.$refs.input.focus()
            })
        },

        handleInputConfirm() {
            const inputValue = this.inputValue
            if (inputValue) {
                this.dynamicTags.push(inputValue)
            }
            this.inputVisible = false
            this.inputValue = ''
            this.dataForm.keyword = this.dynamicTags.join(',')
        },
        // 获取分页数据
        findPage: function(data) {
            this.loading = true
            if (data != null) {
                this.pageRequest = data.pageRequest
            }
            let param = {
                title: this.filters.title
            }
            param = Object.assign(param, this.pageRequest)
            this.$api.article.getArticleList(param).then(res => {
                if (res && !res.success) {
                    this.$message({ message: res.message, type: 'error' })
                    this.loading = false
                    return
                }
                this.page = res.data
                this.loading = false
                this.findCategory()
            }).then(data != null ? data.callback : '')
        },
        findCategory: function() {
            if (this.popupTreeData && this.popupTreeData.length > 0) {
                return
            }
            this.$api.article.getCategoryList().then(res => {
                if (res && !res.success) {
                    this.$message({ message: res.message, type: 'error' })
                    return
                }
                this.popupTreeData = res.data
            })
        },
        // 显示新增界面
        handleAdd: function() {
            this.dialogVisible = true
            this.dataForm = {
                articleId: 0,
                title: '',
                categoryId: 0,
                categoryName: '',
                subtitle: '',
                keyword: '',
                intro: '',
                content: '',
                orderNum: 0,
                author: '',
                source: '',
                recommend: '未推荐',
                ontop: '未置顶',
                url: '',
                pubstatus: '未发布'
            }
            this.dynamicTags = []
        },
        // 显示编辑界面
        handleEdit: function(data) {
            this.$api.article.getArticle({ articleId: data.row.articleId }).then(res => {
                if (!res.success) {
                    this.$message({ message: res.message, type: 'error' })
                    return
                }
                this.dialogVisible = true
                Object.assign(this.dataForm, data.row)
                this.dataForm.content = res.data
                this.dynamicTags = this.dataForm.keyword.split(',')
            })
        },
        // 删除
        handleDelete(data) {
            this.$confirm('确认删除选中记录吗？', '提示', {
                type: 'warning'
            }).then(() => {
                const params = this.getDeleteIds([], data.row)
                this.$api.article.deleteArticle(params).then(res => {
                    if (!res.success) {
                        this.$message({ message: res.message, type: 'error' })
                        return
                    }
                    this.findTreeData()
                    this.$message({ message: '删除成功', type: 'success' })
                })
            })
        },
        // 获取删除的包含子分类的id列表
        getDeleteIds(ids, row) {
            ids.push(row.articleId)
            if (row.children != null) {
                for (let i = 0, len = row.children.length; i < len; i++) {
                    this.getDeleteIds(ids, row.children[i])
                }
            }
            return ids
        },
        // 分类树选中
        handleTreeSelectChange(data, node) {
            console.log(data)
            this.dataForm.categoryId = data.categoryId
            this.dataForm.categoryName = data.categoryName
        },
        selectionChange(selections) {
            console.log(selections)
        },
        handleCurrentHandle: function(val) {
            console.log('handleCurrentHandle>>' + val)
        },
        // 表单提交
        submitForm() {
            var callback = (res) => {
                this.editLoading = false
                if (res.success) {
                    this.$message({ message: '操作成功', type: 'success' })
                    this.$refs['dataForm'].resetFields()
                    this.dialogVisible = false
                } else {
                    this.$message({
                        message: res.message,
                        type: 'error'
                    })
                }
                // 当前页
                this.findPage(null)
            }
            this.$refs['dataForm'].validate(valid => {
                if (valid) {
                    this.$confirm('确认提交吗？', '提示', {}).then(() => {
                        this.editLoading = true
                        const params = Object.assign({}, this.dataForm)
                        // 处理枚举类型, ordinal
                        params.recommend = this.recommendList.findIndex(item => item === params.recommend)
                        params.ontop = this.ontopList.findIndex(item => item === params.ontop)
                        params.pubstatus = this.pubstatusList.findIndex(item => item === params.pubstatus)
                        if (!this.dataForm.articleId) {
                            this.$api.article.saveArticle(params).then(res => {
                                callback(res)
                            })
                        } else {
                            this.$api.article.updateArticle(params).then(res => {
                                callback(res)
                            })
                        }
                    })
                }
            })
        },
        // 初始化表格
        initColums: function() {
            this.columns = [
                { prop: 'articleId', label: 'ID', minWidth: 120 },
                { prop: 'title', label: '标题', minWidth: 120 },
                // {prop: 'categoryName', label: '分类', minWidth: 120},
                { prop: 'subtitle', label: '副标题', minWidth: 120 },
                { prop: 'keyword', label: '关键字', minWidth: 120 },
                // {prop: 'intro', label: '简介', minWidth: 120},
                { prop: 'orderNum', label: '顺序', minWidth: 80 },
                // {prop: 'author', label: '作者', minWidth: 120},
                // {prop: 'source', label: '来源', minWidth: 80},
                { prop: 'recommend', label: '推荐', minWidth: 80 },
                { prop: 'ontop', label: '置顶', minWidth: 80 },
                { prop: 'pubtime', label: '发布时间', minWidth: 150 },
                { prop: 'pubstatus', label: '状态', minWidth: 80 },
                { prop: 'updateTime', label: '更新时间', minWidth: 150 }
            ]
            this.filterColumns = JSON.parse(JSON.stringify(this.columns))
        },
        // 处理表格列过滤显示
        displayFilterColumnsDialog: function() {
            this.$refs.tableColumnFilterDialog.setDialogVisible(true)
        },
        // 处理表格列过滤显示
        handleFilterColumns: function(data) {
            this.filterColumns = data.filterColumns
            this.$refs.tableColumnFilterDialog.setDialogVisible(false)
        },
        onContentChange(val) {
            this.dataForm.content = val
        }
    },
    mounted() {
        this.initColums()
        this.findPage(null)
    }
}
</script>

<style scoped>
  .el-tag + .el-tag {
    margin-left: 10px;
  }
  .button-new-tag {
    margin-left: 10px;
    height: 32px;
    line-height: 30px;
    padding-top: 0;
    padding-bottom: 0;
  }
  .input-new-tag {
    width: 90px;
    margin-left: 10px;
    vertical-align: bottom;
  }
</style>
